#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;

ll check(string &s, char c) {
    vector<int> pos;
    for (int i=0;i<s.size();i++) {
        if (s[i]==c){
            pos.push_back(i);
        }
    }
    int m=pos.size();
    if (m<=1) return 0; 
    int mid=m/2;
    ll res=0;
    for (int i=0;i<m;i++){
        res+=abs(pos[i]-pos[mid])-abs(i-mid);
    }
    return res;
}

void solve() {
    int n;
    string s;
    cin>>n>>s;
    ll r1=check(s,'a');
    ll r2=check(s,'b');
    cout<<min(r1,r2)<<endl;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
}